using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using WeMakeSP.Platform.SharePoint.BusinessEntities;
using WeMakeSP.Platform.SharePoint.Controls;
using WeMakeSP.Platform.SharePoint.Web.UI.Views;
using WeMakeSP.SiteManagement.UI.Models;
using WeMakeSP.SiteManagement.UI.Presenters;
using WeMakeSP.SiteManagement.UI.Views;
using WeMakeSP.Platform.SharePoint.Web;

namespace WeMakeSP.SiteManagement.UI.Web
{
    /// <summary>
    /// The site hierarch interface.
    /// </summary>
    public partial class SiteHierarchy : ViewPageBase<SiteHierarchyPresenter, ISiteHierarchyView>, ISiteHierarchyView
    {
        #region Fields

        /// <summary>
        /// The web configuration field.
        /// </summary>
        private SPWebConfiguration webConfigurationField;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="SiteHierarchy"/> class.
        /// </summary>
        public SiteHierarchy()
        {
            ISiteHierarchyModel model
                = new SiteHierarchyModel(this.Web.Url);

            this.Presenter =
                new SiteHierarchyPresenter(this, model);
        }

        #endregion

        #region Protected Properties

        /// <summary>
        /// Gets a value indicating whether [require site administrator].
        /// </summary>
        /// <value>
        /// <c>True</c> if [require site administrator]; otherwise, <c>false</c>.
        /// </value>
        protected override bool RequireSiteAdministrator
        {
            get
            {
                return true;
            }
        }
        #endregion

        #region Protected Methods

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.Presenter.OnViewInitialized();
            }
            
            this.Presenter.OnViewLoaded();
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets a value indicating whether [inherit logo].
        /// </summary>
        /// <value><c>true</c> if [inherit logo]; otherwise, <c>false</c>.</value>
        public bool InheritLogo
        {
            get
            {
                return
                    this.logoCheckBox.Checked;
            }
        }

        /// <summary>
        /// Gets a value indicating whether [inherit master page].
        /// </summary>
        /// <value><c>true</c> if [inherit master page]; otherwise, <c>false</c>.</value>
        public bool InheritMasterPage
        {
            get
            {
                return
                    this.masterPageCheckBox.Checked;
            }
        }

        /// <summary>
        /// Gets a value indicating whether [inherit theme].
        /// </summary>
        /// <value><c>true</c> if [inherit theme]; otherwise, <c>false</c>.</value>
        public bool InheritTheme
        {
            get
            {
                return
                    this.inheritThemeCheckBox.Checked;
            }
        }

        /// <summary>
        /// Gets the root web id.
        /// </summary>
        /// <value>The root web id.</value>
        public Guid RootWebId
        {
            get
            {
                return
                    new Guid(this.treeViewDataSource.RootWebId);
            }

            set
            {
                this.treeViewDataSource.RootWebId = value.ToString();
            }
        }

        /// <summary>
        /// Gets the selected web ids.
        /// </summary>
        /// <value>The selected web ids.</value>
        public List<Guid> SelectedWebIds
        {
            get
            {
                return
                    this.GetSelectedWebIds();
            }
        }

        /// <summary>
        /// Gets or sets the web configuration.
        /// </summary>
        /// <value>The web configuration.</value>s
        public SPWebConfiguration WebConfiguration
        {
            get
            {
                return
                    this.webConfigurationField;
            }
            set
            {
                this.webConfigurationField = value;
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Redirects to settings page.
        /// </summary>
        public void RedirectToSettingsPage()
        {
            Response.Redirect(this.Web.Url + PageUrlConstants.WebSettings);
        }

        #endregion

        #region Protected Methods

        /// <summary>
        /// Submits the click event handler.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void SubmitClickEventHandler(object sender, EventArgs e)
        {
            this.Presenter.ProcessRequest();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Extracts the web id.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <returns></returns>
        private Guid ExtractWebId(TreeNode node)
        {
            string pattern = @"WebNode:?(?<webid>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?)$";

            Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);

            Match match = reg.Match(node.DataPath);

            // TODO Create an exception.

            if (match.Success != true)
            {
                throw new Exception(node.DataPath);
            }

            string
                webIdText = match.Groups["webid"].Value;

            Guid webId =
                new Guid(webIdText);

            return webId;
        }

        /// <summary>
        /// Gets the selected web ids.
        /// </summary>
        private List<Guid> GetSelectedWebIds()
        {
            List<Guid> webIds =
               new List<Guid>();

            // Get the checked items only.

            TreeNodeCollection checkedNodes = this.siteHierarchyTreeView.CheckedNodes;

            // For each checked node.

            foreach (TreeNode node in checkedNodes)
            {
                // Extract thw web id and add it to the collection.

                webIds.Add(this.ExtractWebId(node));
            }

            return webIds;
        }

        #endregion
    }
}